package com.ktjiaoyu.server.config.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.secret}")
    private String secret;

    //1.生成token
    //2.解析token
    //3.验证token是否有效
    public String genegrateToken(UserDetails userDetails){
        JwtBuilder jwtBuilder= Jwts.builder();

        Map<String,Object> map=new HashMap<>();
        map.put("sub",userDetails.getUsername());

        long ex=System.currentTimeMillis()+expiration*1000;
        jwtBuilder.setClaims(map)
                .setExpiration(new Date(ex))//设置过期时间
                .setIssuedAt(new Date())//设置生效时间
                .signWith(SignatureAlgorithm.HS256,secret);//设置加密算法和秘钥;
        return jwtBuilder.compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public String getUserNameFromToken(String token){
        Claims body = getClaimsFromToken(token);
        return body.getSubject();
    }

    private Claims getClaimsFromToken(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    public boolean validateToken(String token,UserDetails userDetails){
        //token有效期是否还在
        Claims claims = getClaimsFromToken(token);
        boolean flag1=claims.getExpiration().after(new Date());
        //token的用户名是否正确
        String username = getUserNameFromToken(token);
        boolean flag2=username.equals(userDetails.getUsername());

        return flag1&&flag2;
    }
}
